package cn.org.donald.sensitive.factory;

import cn.org.donald.sensitive.model.FactoryEnum;
import cn.org.donald.sensitive.util.StringUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Donald
 * @since 2023-11-10 13:40:04
 **/
public class TxtFindSensitive extends IFindSensitive {

    public TxtFindSensitive(Path filePath, FactoryEnum factoryEnum) {
        super(filePath, factoryEnum);
    }

    @Override
    public List<String> getSensitiveString(List<String> ruleRegexList) {
        try (BufferedReader bufferedReader = Files.newBufferedReader(super.getFilePath());
             Stream<String> lines = bufferedReader.lines()) {
            return lines.flatMap(line -> super.findSensitiveInString(ruleRegexList, line)).collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void replace(List<String> ruleRegexList, Path destPath) {
        try {
            Files.deleteIfExists(destPath);
            Files.createDirectories(destPath.getParent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (BufferedReader bufferedReader = Files.newBufferedReader(super.getFilePath());
             BufferedWriter bufferedWriter = Files.newBufferedWriter(destPath, StandardOpenOption.CREATE_NEW)
        ) {
            String line;
            String regex = String.join("|", ruleRegexList);
            while ((line = bufferedReader.readLine()) != null) {
                String replacement = StringUtil.replaceTargetToStar(line, regex);
                bufferedWriter.write(replacement);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
